﻿using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Unicode;
using System.Threading.Tasks;

namespace Publicuse.WebCore.JsonExtend
{
    /// <summary>
    /// 使用NewtonsoftJson替换掉默认的json序列化组件
    /// </summary>
    public static class JsonExtension
    {
        /// <summary>
        /// 配置Json格式化
        /// </summary>
        /// <param name="services"></param>
        public static IMvcBuilder AddJsonExt(this IMvcBuilder builder)
        {
            return builder.AddNewtonsoftJson(options =>
             {
                 //忽略循环引用
                 options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                 //设置时间格式
                 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";

                 //修改时间的序列化方式
                 options.SerializerSettings.Converters.Add(new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });

                 //数据格式首字母小写
                 options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                 //数据格式按原样输出
                 options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                 //忽略空值
                 options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
             }).AddJsonOptions(options =>
             {
                 //解决输出的json中文被编码（乱码）的问题
                 options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
             });
        }
    }
}
